#include <iostream>
#include <unistd.h>
#include <fcntl.h>

void set_nonblock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        perror("fcntl failed");
        return;
    }

    if (fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0)
    {
        perror("fcntl failed");
        return;
    }
}

int main()
{
    char buf[64] = {0};

    set_nonblock(0);

    while (true)
    {
        std::cout << "please input:> ";
        fflush(stdout);

        ssize_t n = read(0, buf, sizeof(buf) - 1);
        if (n > 0)
        {
            buf[n - 1] = 0;
            std::cout << buf << std::endl;
        }
        else if (n == 0)
        {
            perror("end of file");
            break;
        }
        else
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK) // 非阻塞数据未就绪返回
            {
                continue;
            }
            else if (errno == EINTR) // IO被信号中断返回
            {
                continue;
            }
            else
            {
                perror("read error");
                break;
            }
        }
    }

    return 0;
}
